package es.uc3m.ce.practice1.ex1;

/**
 * Class to test the precision of single and double point operations in Java.
 * The program will execute a loop to find the result of a series until the value of Sn is equal Sn-1, which will mean that Java has reached its maximum precision.
 * After running this algorithm, the output of the program will be the maximum number of iterations, before reaching the previous condition, for both single and double precision and the total value of the series.
 * @author Adrián Gil Moral - 100293146
 * @author Rafael Medina García - 100292314
 * @version 1.0.0
 */
public class Series {
	
	/**
	 * Method to perform the calculation of the series in double precision
	 */
	public static void dAddition() {		
		/* Variables */
		double sum = 0; // Value of the series
		double temp = 1; // Temporal variable. Begins with value 1 so that the condition is not met at start
		int n = 0; // Actual position in the series
		
		/* Perform the calculations */
		while(sum != (sum-temp)) { // This loop continues until Sn is equal to Sn-1
			temp = (1/Math.pow(2, n)); // Store the actual step in a temporal variable
			sum += temp; // Add the step result to the total result
			n++; // Next step
		}
		
		/* Print number of iterations */
		System.out.println("Iterations: " + (n-1)); // It will be n-1 because that is the maximum number of iterations BEFORE reaching the same value
		/* Print the value of the series */
		System.out.println("Total value: " + sum);
	}
	
	/**
	 * Method to perform the calculation of the series in single precision
	 */
	public static void fAddition() {		
		/* Variables */
		float sum = 0; // Total value of the series
		float temp = 1; // Temporal variable. Begins with value 1 so that the condition is not met at start
		int n = 0; // Actual position in the series
		
		/* Perform the calculations */
		while(sum != (sum-temp)) { // This loop continues until Sn is equal to Sn-1
			temp = (1/(float)Math.pow(2, n)); // Store the actual step in a temporal variable
			sum += temp; // Add the step result to the total result
			n++; // Next step
		}
		
		/* Print number of iterations */
		System.out.println("Iterations: " + (n-1)); // It will be n-1 because that is the maximum number of iterations BEFORE reaching the same value
		/* Print the value of the series */
		System.out.println("Total value: " + sum);
	}
	
	public static void main(String[] args) {
		System.out.println("---Single precision---");
		fAddition();
		System.out.println("---Double precision---");
		dAddition();
	}
}
